<template>
    <div class="freightRateList">
         <Card >
            <Row>
                <Col span="24">
                    <Form ref="freightRateListRef" :model="freightRateListForm" :rules="freightRateListRule">
                        <div class="createMall-box">
                            <Row class="mt-10">
                                <Col span="22">
                                    <Form-item prop="searchModel">
                                        <Input placeholder="请输入运费模板名称" :maxlength=20 v-model="freightRateListForm.searchModel" style="width:200px"  @on-enter="searchEnter" enter-button/> 注:按回车键进行搜索
                                    </Form-item>    
                                </Col>
                                <Col span="2">
                                     <Button type="primary" @click.native="openAddFreight">添加</Button>
                                </Col>
                            </Row> 
                        </div>
                    </Form>
                    <Table :columns="freightRateListColumns" :data="freightRateListData"></Table>
                    <Page
                        ref="freightRateListPage"
                        :total="searchData.totalElements"
                        :page-size="searchData.size"
                        @on-change="changePage"
                        @on-page-size-change="changePageSize"
                        show-sizer
                        :page-size-opts="[5, 10, 20, 30, 40]"
                        show-total
                        style="margin-top:30px;text-align:center;">
                    </Page>
                    <!-- 新增/编辑弹窗 -->
                     <Modal v-model="addFreightRateModel" :mask-closable="false">
                        <p slot="header">
                            <span>{{freightTitle}}</span>
                        </p>
                        <div>
                            <Form ref="addFreightRateRef" :model="addFreightRateForm" :rules="addFreightRateRule" :label-width="100">
                                <Form-item label="模板名称" prop="name">
                                    <Input placeholder="请输入模板名称" :maxlength=20 v-model="addFreightRateForm.name" style="width:400px"/>
                                </Form-item>
                                <Form-item label="费用计算方式">
                                    <Radio-group v-model="addFreightRateForm.typeName" @on-change="chooseRadio">
                                            <Radio label="按商品件数计算">
                                                <span>按商品件数计算</span>
                                            </Radio>
                                            <Radio label="按商品重量计算">
                                                <span>按商品重量计算</span>
                                            </Radio>
                                    </Radio-group>
                                </Form-item>
                                <Form-item label="首重(kg)/首件" prop="firstAmount">
                                    <Input placeholder="请输入重量" v-model="addFreightRateForm.firstAmount" style="width:400px"/>
                                </Form-item>
                                <Form-item label="首费(元)" prop="firstPrice">
                                    <Input placeholder="请输入首费" v-model="addFreightRateForm.firstPrice" style="width:400px"/>
                                </Form-item>
                                <Form-item label="续重(kg)/首件" prop="continuedAmount">
                                    <Input placeholder="请输入重量" v-model="addFreightRateForm.continuedAmount" style="width:400px"/>
                                </Form-item>
                                <Form-item label="续费(元)" prop="continuedPrice">
                                    <Input placeholder="请输入首费" v-model="addFreightRateForm.continuedPrice"  style="width:400px"/>
                                </Form-item>
                                <Form-item label="目的地">
                                    <div>
                                        <Cascader :data="continueCityList" change-on-select @on-change="changeArea" v-model="changeAreaList"></Cascader>
                                        <Button type="primary" @click.native="addCity">添加</Button>
                                    </div>
                                    <div>
                                    <Tag v-for="(item,index) in addFreightRateForm.freightTemplateAreasList" :key="index" :name="index"
                                     closable v-model="addFreightRateForm.freightTemplateAreasList" @on-close="deleteCity(index)">{{ item.areaName }}</Tag>
                                    </div>
                                </Form-item>
                            </Form>
                        </div>
                        <div slot="footer" class="footer ta-c">
                            <Button type="primary" @click.native="submitFreight('addFreightRateRef')" :disabled="cityLoading">提交</Button>
                            <Button type="primary" @click.native="closetFreight">取消</Button>
                        </div>
                    </Modal>
                </Col>
            </Row>
        </Card>
        <Spin size="large" fix v-show="showSpin">
            请稍后....
        </Spin>
    </div>
</template>
<script>
export default {
    name: 'freightRateList',
    props: ['shopIds'],
    data () {
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('此项为必填项'));
            } else {
                var passReg = /^(([1-9]\d{0,12})|0)(\.\d{0,2})?$/;
                if (!passReg.test(value)) {
                    callback(new Error('格式有误'));
                } else {
                    callback();
                }
            }
        };
        return {
            shopId: '',
            freightTitle: '添加运费模板',
            freightRateListForm: {
                searchModel: '' // 搜索框
            },

            showSpin: false,
            // 分页
            searchData: {
                name: '',
                totalElements: 1,
                page: 0,
                size: 10
            },
            freightRateListRule: {
                searchModel: [
                    { message: '请输入运费模板名称', trigger: 'blur' },
                    { type: 'string', max: 20, message: '最多输入20个字', trigger: 'blur' },
                    { type: 'string', pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]*$/, message: '只能输入汉字数字英文', trigger: 'blur' }
                ]
            },
            // 列表树
            freightRateListColumns: [
                {
                    title: '编号',
                    align: 'center',
                    minWidth: 150,
                    key: 'templateNo',
                    tooltip: true
                },
                {
                    title: '模板名称',
                    key: 'name',
                    minWidth: 120,
                    align: 'center',
                    tooltip: true
                },
                {
                    title: '计价方式',
                    key: 'typeName',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '数量(件)',
                    key: 'firstAmount',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '起步价',
                    key: 'firstPrice',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '增加数量(件)',
                    key: 'continuedAmount',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '加价',
                    key: 'continuedPrice',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '地区',
                    key: 'freightTemplateAreasListLength',
                    align: 'center',
                    minWidth: 150,
                    render: (h, params) => {
                        console.log(params.row.freightTemplateAreasList.length, 'params.row');
                        return h('span', {
                            props: {
                                value: params.row.freightTemplateAreasList.length
                            }
                        }, params.row.freightTemplateAreasList.length);
                    }
                },
                {
                    title: '更新时间',
                    key: 'createTime',
                    align: 'center',
                    minWidth: 150
                },
                {
                    title: '是否启用',
                    key: 'isActive',
                    align: 'center',
                    minWidth: 150,
                    render: (h, params) => {
                        return h('i-switch', {
                            props: {
                                value: params.row.isActive
                            },
                            on: {
                                'on-change': (value) => {
                                    console.log(value, 'value');
                                    this.SwitchChange(params.row.id, value);
                                }
                            }
                        }, [
                            h('span', {
                                slot: 'open',
                                domProps: {
                                    innerHTML: '开'
                                }
                            }),
                            h('span', {
                                slot: 'close',
                                domProps: {
                                    innerHTML: '关'
                                }
                            })
                        ]);
                    }
                }, {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: 200,
                    render: (h, params) => {
                        return h('div', [
                            h('span', {
                            }, [
                                h('Button', {
                                    props: {
                                        align: 'center',
                                        type: 'primary'
                                    },
                                    on: {
                                        click: () => {
                                            this.writefreight(params.row);
                                        }
                                    }

                                }, '编辑')
                            ]),
                            h('span', {
                            }, [
                                h('Button', {
                                    props: {
                                        align: 'center',
                                        type: 'primary'
                                    },
                                    on: {
                                        click: () => {
                                            this.deletefreight(params.row.id);
                                        }
                                    }

                                }, '删除')
                            ])
                        ]);
                    }
                }
            ],
            // 列表树data
            freightRateListData: [],
            // 添加运费模板弹窗
            addFreightRateModel: false,
            addFreightRateForm: {
                name: '', // 名称
                typeCode: '', // 计费编码
                typeName: '', // 计算方式
                firstAmount: '', // 首重
                firstPrice: '', // 首费
                continuedAmount: '', // 续重
                continuedPrice: '', // 续费,
                freightTemplateAreasList: []
            },
            addFreightRateRule: {
                name: [
                    { required: true, message: '请输入运费模板名称', trigger: 'blur' },
                    { type: 'string', max: 20, message: '最多输入20个字', trigger: 'blur' },
                    { type: 'string', pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]*$/, message: '只能输入汉字数字英文', trigger: 'blur' }
                ],
                firstAmount: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                firstPrice: [
                    { validator: validatePass, trigger: 'blur' }

                ],
                continuedAmount: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                continuedPrice: [
                    { validator: validatePass, trigger: 'blur' }
                ]

            },
            // 地址多选
            continueCityList: [],
            // 提交时的loading 状态
            cityLoading: false,
            cityList: {},
            changeAreaList: []

        };
    },
    mounted () {
        this.shopId = this.$route.query.id;
        this.findShop();
        this.loadAreaData();
    },
    methods: {
        findShop () {
            depot.get({
                url: this.URL.EC_SELLER.FIND_BY_NAME_LINK_PAGE + '?shopId=' + this.shopId +
                '&page=' + this.searchData.page + '&size=' + this.searchData.size + '&nameLike=' + this.freightRateListForm.searchModel,
                cb: (data) => {
                    if (data.code === 0) {
                        this.freightRateListData = data.data.content;
                        this.searchData.size = data.data.size;
                        this.searchData.totalElements = data.data.totalElements;
                    }
                },
                ce: (error) => {
                    this.$Message.error(data.message);
                }
            });
        },
        searchEnter () {
            console.log(this.freightRateListForm.searchModel, 'searchModel');
            this.findShop();
        },
        // 分页
        changePage (val) {
            this.searchData.page = val - 1;
            this.findShop();
            localStorage.setItem('page', this.searchData.page);
        },
        changePageSize (val) {
            this.searchData.size = val;
            localStorage.setItem('size', this.searchData.size);
            this.findShop();
        },
        // 查询所有省市区
        loadAreaData () {
            depot.get({
                url: this.URL.DATA.FIND_ALL_BY_PARENT_ID,
                config: {
                    params: {
                        parentId: 1
                    }
                },
                cb: (data) => {
                    this.showSpin = false;
                    if (data.code === 0) {
                        this.continueCityList = data.data;
                    } else if (data.code === 999) {
                        this.$Message.error(data.message);
                    }
                },
                ce: (error) => {
                }
            });
        },
        //  费用计算方式
        chooseRadio (val) {
            console.log(val);
            if (val == '按商品件数计算') {
                this.addFreightRateForm.typeName = '按商品件数计算';
                this.addFreightRateForm.typeCode = 'NUM';
            } else if (val == '按商品重量计算') {
                this.addFreightRateForm.typeName = '按商品重量计算';
                this.addFreightRateForm.typeCode = 'WEIGHT';
            }
        },
        // 地址选择
        changeArea (val, selectedData) {
            this.cityList = {};
            if (selectedData[0]) {
                this.cityList.areaId = selectedData[0].id;
                this.cityList.areaName = selectedData[0].name;
            }
            if (selectedData[0] && selectedData[1]) {
                this.cityList.areaId = selectedData[1].id;
                this.cityList.areaName = selectedData[0].name + '/' + selectedData[1].name;
            }
            if (selectedData[0] && selectedData[1] && selectedData[2]) {
                this.cityList.areaId = selectedData[2].id;
                this.cityList.areaName = selectedData[0].name + '/' + selectedData[1].name + '/' + selectedData[2].name;
            }
        },
        addCity () {
            let vue = this;
            console.log(vue.addFreightRateForm.freightTemplateAreasList);
            console.log(this.cityList, 333);
            if (!vue.addFreightRateForm.freightTemplateAreasList) {
                vue.addFreightRateForm.freightTemplateAreasList = [];
            }
            vue.addFreightRateForm.freightTemplateAreasList.push(this.cityList);
            vue.addFreightRateForm.freightTemplateAreasList = JSON.parse(JSON.stringify(vue.addFreightRateForm.freightTemplateAreasList));
            vue.$forceUpdate();
            console.log(vue.addFreightRateForm.freightTemplateAreasList, '100100');
        },
        // 删除地址
        deleteCity (key) {
            // const key = this.addFreightRateForm.freightTemplateAreasList.indexOf(index);
            console.log(key, 'ine');
            this.addFreightRateForm.freightTemplateAreasList.splice(key, 1);
        },
        // 是否启用
        SwitchChange (id, value) {
            // UPDATE_ACTIVEBY_IDS?isActive=true
            console.log(value, 'value');
            let vue = this;
            let ids = [id];
            console.log(ids, 'ids');
            this.showSpin = true;
            depot.post({
                url: this.URL.EC_SELLER.UPDATE_ACTIVEBY_IDS + '?isActive=' + value,
                data: ids,
                cb: (data) => {
                    if (data.code === 0) {
                        this.showSpin = false;
                        this.$Message.success('修改状态成功');
                        this.refresh();
                    } else {

                    }
                }
            });
        },

        // 新增弹窗
        openAddFreight () {
            this.freightTitle = '新增运费模板';
            if (this.freightTitle == '新增运费模板') {
                this.addFreightRateForm = {};
                // this.changeAreaList = [];
            } else {
            }
            this.addFreightRateModel = true;
        },
        writefreight (params) {
            let vue = this;
            this.freightTitle = '编辑运费模板';
            vue.addFreightRateForm = params;
            this.addFreightRateForm.freightTemplateAreasList = params.freightTemplateAreasList;

            this.addFreightRateModel = true;
        },
        deletefreight (params) {
            // DEL_FREIGHT_TEMPLATE_BY_IDS
            let ids = [params];
            this.showSpin = true;
            depot.post({
                url: this.URL.EC_SELLER.DEL_FREIGHT_TEMPLATE_BY_IDS,
                data: ids,
                cb: (data) => {
                    if (data.code === 0) {
                        this.$Message.success('删除成功');
                        this.showSpin = false;
                        this.refresh();
                    } else if (data.code === 999) {
                        this.$Message.error(data.message);
                        this.showSpin = false;
                    }
                },
                ce: (error) => {
                }
            });
        },

        //  取消
        closetFreight () {
            this.addFreightRateModel = false;
            if (this.freightTitle == '新增运费模板') {
                this.$refs['addFreightRateRef'].resetFields();
                this.addFreightRateForm.freightTemplateAreasList = [];
            } else {

            }
        },
        // 提交
        submitFreight (name) {
            console.log(this.addFreightRateForm, 'WEIGHT/NUM');
            this.addFreightRateForm.shopId = this.shopId;
            this.addFreightRateForm.isBoss = false;
            if (this.addFreightRateForm.typeName == '按商品件数计算') {
                this.addFreightRateForm.typeCode = 'NUM';
            } else {
                this.addFreightRateForm.typeCode = 'WEIGHT';
            }
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.cityLoading = true;
                    depot.post({
                        url: this.URL.EC_SELLER.SAVE_FREIGHT_TEMPLATE,
                        data: this.addFreightRateForm,
                        cb: (data) => {
                            if (data.code === 0) {
                                this.$Message.success('提交成功');
                                this.refresh();
                                this.cityLoading = false;
                                this.addFreightRateModel = false;
                                this.$refs['addFreightRateRef'].resetFields();
                                this.addFreightRateForm.freightTemplateAreasList = [];
                            } else if (data.code === 999) {
                                this.$Message.error(data.message);
                                this.showSpin = false;
                                this.cityLoading = false;
                                this.addFreightRateModel = false;
                            }
                        },
                        ce: (error) => {
                            this.showSpin = false;
                            this.addFreightRateModel = false;
                        }
                    });
                }
            });
        },

        // 刷新
        refresh () {
            this.findShop();
        }
    },
    watch: {
        shopIds (newVal, oldVal) {
            if (newVal) {
                this.shopId = newVal;
            }
            console.log(this.shopId, 'sellerFreightTemplate');
            this.findShop();
        }
    }
};
</script>

<style lang="less" scoped>
    .freightRateList{

    }
</style>

